<template>
    <div class="article-edit">
        <el-card class="!border-none" shadow="never">
            <el-page-header :content="$route.meta.title" @back="$router.back()"/>
            <div class="btnR" v-if="formData.status == 1">
                <template v-if="isDisabled">
                    <el-button type="primary" @click="handleEdit">编辑</el-button>
                    <el-button type="danger" plain @click="handleCheck(3)">审核驳回</el-button>
				    <el-button type="primary" @click="handleCheck(2)">审核通过</el-button>
                </template>
				<template v-if="!isDisabled">
                    <el-button type="danger" plain @click="handleCancel">取消</el-button>
				    <el-button type="primary" @click="handleSave">保存</el-button>
                </template>
			</div>
        </el-card>

        <el-tabs v-model="defaultTab" >
            <el-tab-pane label="需求信息" name="demand_info">

                <el-form
                    ref="formRef"
                    :model="formData"
                    :rules="rules"
                    label-width="130"
                    :validate-on-rule-change="false"
                >
                    <el-card class="!border-none mt-4" shadow="never">
                        <div class="font-medium mb-7">基础信息</div>
                        <div class="flex flex-wrap">
                            <el-form-item class="w-2/6" label="需求状态：">
                                <div class="w-80">{{ typeTxt(formData.status) }}</div>
                            </el-form-item>
                            <el-form-item class="w-2/6" label="创建时间：">
                                <div class="w-80">{{ formData.create_time }}</div>
                            </el-form-item>
                            <el-form-item class="w-2/6" label="发布人：">
                                <div class="w-80">{{ formData.user.real_name }}</div>
                            </el-form-item>
                            <el-form-item class="w-2/6" label="发布手机号：">
                                <div class="w-80">{{ formData.user.account }}</div>
                            </el-form-item>
                            <el-form-item class="w-2/6" label="城市：" prop="area_id">
                                <div class="w-80">
                                    <el-select-v2
                                        v-model="formData.area_id"
                                        filterable
                                        clearable
                                        :options="optionCity"
                                        placeholder="请选择"
                                        class="w-[180px]"
                                        :height="280"
                                        :disabled="isDisabled"
                                    />
                                </div>
                            </el-form-item>
                            <el-form-item class="w-2/6" label="需求来源：">
                                <div class="w-80">{{ formData.source_type == 1 ? '平台需求': 'CRM需求' }}</div>
                            </el-form-item>
                        </div>
                    </el-card>
                    <el-card class="!border-none mt-4" shadow="never">
                        <div class="font-medium mb-7">业务信息</div>
                        <div class="flex">
                            <el-form-item class="w-2/6" label="客户年龄：">
                                <div class="w-80">{{ formData.age?formData.age:'-' }}</div>
                            </el-form-item>
                            <el-form-item class="w-2/6" label="所需额度：">
                                <div class="w-80">{{ formData.quota > 0?formData.quota+'万':'-' }}</div>
                            </el-form-item>
                            <el-form-item class="w-2/6" label="业务类型：">
                                <el-tooltip v-if="formData.cates.length > 0" effect="dark" :content="catesTxt(formData.cates)" placement="top">
                                    <template #content>
                                        <div class="w-52">{{ catesTxt(formData.cates) }}</div>
                                    </template>
                                    <div class="w-80 content-yw">{{ formData.cates.length > 0? catesTxt(formData.cates): '-'  }}</div>
                                </el-tooltip>
                                <div v-else>-</div>
                            </el-form-item>
                        </div>
                        <div class="flex">
                            <el-form-item class="w-2/6" label="征信状况：">
                                <div class="w-80">{{ creditTxt(formData.credit_status) }}</div>
                            </el-form-item>
                        </div>
                        <el-form-item label="需求描述" prop="description">
                            <div class="w-1/2">
                                <el-input
                                type="textarea"
                                :autosize="{ minRows: 10}"
                                placeholder="请输入内容"
                                v-model="formData.description"
                                :disabled="isDisabled"
                                />
                            </div>
                        </el-form-item>
                        <div class="font-medium mb-7">语音文件</div>
                        <div class="flex flex-wrap" v-if="audioList.length != 0">
                            <el-card v-for="(audio, index) in audioList" :key="index" class="audio-card">
                                <div class="audio-info">
                                    <!-- <span>{{ audio.name }}</span> -->
                                    <span>语音 {{ index+1 }}</span>
                                    <div class="audio-controls">
                                    <el-button
                                        size="small"
                                        :type="isPlaying[index] ? 'danger' : 'primary'"
                                        @click="togglePlay(index)"
                                    >
                                        {{ isPlaying[index] ? '暂停' : '播放' }}
                                    </el-button>
                                    <el-button
                                        size="small"
                                        type="info"
                                        @click="stopAudio(index)"
                                        :disabled="!isPlaying[index]"
                                    >
                                        停止
                                    </el-button>
                                    </div>
                                </div>
                                <el-slider
                                    v-model="progress[index]"
                                    :min="0"
                                    :max="audio.duration"
                                    @input="seekAudio(index, $event)"
                                    class="progress-slider"
                                />
                                <div class="flex justify-between items-center">
                                    <span class="time-display">{{ audio.new_size }}M</span>
                                    <span class="time-display">
                                        {{ formatTime(progress[index]) }} / {{ formatTime(audio.duration) }}
                                    </span>
                                </div>
                                
                            </el-card>
                        </div>
                    </el-card>
                    <el-card class="!border-none mt-4" shadow="never">
                        <div class="font-medium mb-7">附件</div>
                        <el-form-item label="已上传文件" >
                            <div>
                                <div class="content">
                                    <div class="content-item" v-for="(item,index) in formData.attachments">
                                        <div class="item-del" @click="onDel(index)">
                                            <!-- <img class="del-img" src="https://files.onestep6.com/2024/wxicon/img/file-del.png" alt=""> -->
                                             <el-icon size="20px"><CircleCloseFilled /></el-icon>
                                        </div>
                                        <div v-if="item.type_link != 1" class="item-content" @click="onSee(item.url)">
                                            <img class="item-type" :src="item.type_link" alt="">
                                            <div>
                                                <div>{{ item.name }}</div>
                                                <div>{{ item.new_size }}M</div>
                                            </div>
                                        </div>
                                        <div v-if="item.type_link == 1">
                                            <el-image style="width: 80px; height: 80px"
                                                :src="item.url"
                                                :zoom-rate="1.2"
                                                :max-scale="7"
                                                :min-scale="0.2" 
                                                fit="contain"
                                                :preview-teleported="true"
                                                :preview-src-list="[item.url]">
                                            </el-image>
                                        </div>
                                    </div>
                                </div>
                                <div v-if="formData.attachments.length == 0">无</div>
                            </div>
                        </el-form-item>
                        <upload
                            class="mr-3"
                            type="file"
                            :show-progress="true"
                            @success="refresh"
                            :disabled="isDisabled"
                        >
                            <el-button type="primary" style="margin-left: 50px;" :disabled="isDisabled">上传附件</el-button>
                        </upload>
                        
                        <!-- <el-form-item label="图片" >
                            <div class="w-1/2">
                                <material-picker v-model="file_img" type="image" :limit="100"/>
                            </div>
                        </el-form-item>
                        <el-form-item label="文件" >
                            <div class="w-1/2">
                                <material-picker v-model="file_list" type="file" :limit="100"/>
                            </div>
                        </el-form-item> -->
                    </el-card>
                </el-form>

            </el-tab-pane>
            <!-- 对接信息 -->
            <el-tab-pane v-if="isDock" label="对接信息" name="docking_info">
                <el-card class="!border-none mt-4" shadow="never">
                    <div class="flex items-center">
                        <div class="txt-content">通知人数（{{ pager.extend.notify_count || 0 }}）</div>
                        <div class="flex items-center ml-8 mr-8">
                            <div class="arrow-left"></div>
                            <div class="arrow-container"></div>
                        </div>
                        <div class="txt-content">查看人数（{{ pager.extend.read_count || 0 }}）</div>
                        <div class="flex items-center ml-8 mr-8">
                            <div class="arrow-left"></div>
                            <div class="arrow-container"></div>
                        </div>
                        <div class="txt-content">对单人数（{{ pager.extend.abutment_count || 0 }}）</div>
                        <div class="flex items-center ml-8 mr-8">
                            <div class="arrow-left"></div>
                            <div class="arrow-container"></div>
                        </div>
                        <div class="txt-content">发起合作人数（{{ pager.extend.launch_cooperation_count || 0 }}）</div>
                        <div class="flex items-center ml-8 mr-8">
                            <div class="arrow-left"></div>
                            <div class="arrow-container"></div>
                        </div>
                        <div class="txt-content">已合作人数（{{ pager.extend.cooperation_count || 0 }}）</div>
                    </div>
                </el-card>

                <el-card class="!border-none mt-4" shadow="never">
                    <el-form ref="formQuery" class="mb-[16px]" :model="queryParams" :inline="true">
                        <el-form-item label="需求状态">
                            <el-select class="w-60" v-model="queryParams.is_read" placeholder="请选择" clearable filterable>
                                <el-option label="全部" value />
                                <el-option label="未查看" :value="0" />
                                <el-option label="已查看" :value="1" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="对接状态">
                            <el-select class="w-60" v-model="queryParams.abutment_status" placeholder="请选择" clearable filterable>
                                <el-option label="全部" value />
                                <el-option label="未对接" :value="0" />
                                <el-option label="对接中" :value="1" />
                                <el-option label="已完结" :value="2" />
                                <el-option label="取消对接" :value="3" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="合作状态">
                            <el-select class="w-60" v-model="queryParams.cooperation_status" placeholder="请选择" clearable filterable>
                                <el-option label="全部" value />
                                <el-option label="未发起" :value="1" />
                                <el-option label="待确认" :value="2" />
                                <el-option label="已合作" :value="3" />
                                <el-option label="已取消" :value="4" />
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="resetPage">查询</el-button>
                            <el-button @click="resetParams">重置</el-button>
                        </el-form-item>
                    </el-form>
                    
                    <el-table v-loading="pager.loading" :data="pager.lists" border style="width: 100%">
                        <el-table-column type="index" :index="indexAdd" label="序号" min-width="80" />
                        <el-table-column prop="channelExtra.real_name" label="姓名" min-width="120" >
                            <template #default="{ row }">
                                <el-button type="primary" link @click="onChannel(row)">{{ row.channelExtra.real_name }}</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="头像" prop="channelExtra.avatar" min-width="90">
                            <template #default="{ row }">
                                <image-contain
                                    v-if="row.channelExtra.avator"
                                    :src="row.channelExtra.avator"
                                    :width="45"
                                    :height="45"
                                    :preview-src-list="[row.channelExtra.avator]"
                                    preview-teleported
                                    fit="contain"
                                />
                            </template>
                        </el-table-column>
                        <el-table-column prop="channelExtra.account" label="手机号" min-width="180" />
                        <el-table-column prop="name" label="查看状态" min-width="180">
                            <template #default="{ row }">
                                <el-button link v-if="row.is_read == 0">未查看</el-button>
                                <el-button type="primary" link v-if="row.is_read == 1" @click="recordShow(row)">已查看</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" label="对接状态" min-width="180" >
                            <template #default="{ row }">
                                <el-button link v-if="row.status == 0">未对接</el-button>
                                <el-button type="primary" link v-if="row.status == 1" @click="dockShow(row)">对接中</el-button>
                                <el-button type="primary" link v-if="row.status == 2" @click="dockShow(row)">已完结</el-button>
                                <el-button type="primary" link v-if="row.status == 3" @click="dockShow(row)">取消对接</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" label="合作状态" min-width="180" >
                            <template #default="{ row }">
                                <el-button link v-if="row.cooperation_status == 1">未发起</el-button>
                                <el-button type="primary" v-if="row.cooperation_status == 2" link @click="cooperateShow(row)">待确认</el-button>
                                <el-button type="primary" v-if="row.cooperation_status == 3" link @click="cooperateShow(row)">已合作</el-button>
                                <el-button type="primary" v-if="row.cooperation_status == 4" link @click="cooperateShow(row)">已取消</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="flex justify-end mt-4">
                        <pagination v-model="pager" @change="getLists" />
                    </div>
                </el-card>

            </el-tab-pane>
            <!-- 操作记录 -->
            <el-tab-pane label="操作记录" name="record_info">
                <el-card class="!border-none mt-4" shadow="never">
                    <el-table :data="formData.operation_records" border style="width: 100%">
                        <el-table-column prop="action_type" label="操作类型" min-width="180" >
                            <template #default="{ row }">
                                <span v-if="row.action_type == 1">新增</span>
                                <span v-if="row.action_type == 2">修改</span>
                                <span v-if="row.action_type == 3">审核</span>
                                <span v-if="row.action_type == 4">关闭</span>
                                <span v-if="row.action_type == 5">完结</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="content" label="操作内容" min-width="180" >
                            <template #default="{ row }">
                                <div v-if="row.action_type == 1">创建需求</div>
                                <div v-if="row.action_type == 2">
                                    <!-- 新增 -->
                                    <div class="mb-2" v-for="(item,index) in row.add_list" :key="index">
                                        <div v-if="item.newValue == item.oldValue"></div>
                                        <div v-else-if="!Array.isArray(item.newValue)" class="flex align-center">{{ `“${item.name}”新增了 ` }}</div>
                                        <div v-else-if="Array.isArray(item.newValue) && item.field != 'universal_category_id'">
                                            <div class="flex align-center">
                                                <div style="line-height: 45px;">{{ `“${item.name}”新增了 ` }}
                                                <template v-for="(itemC,indexC) in item.newValue" :key="indexC">
                                                    <image-contain
                                                        v-if="itemC.type_link == 1"
                                                        :src="itemC"
                                                        :width="60"
                                                        :height="45"
                                                        :preview-src-list="[itemC]"
                                                        preview-teleported
                                                        fit="contain"
                                                    />
                                                    <span v-if="itemC.type_link != 1">{{ itemC.name }}</span>
                                                </template>
                                                </div>
                                            </div>
                                            
                                        </div>
                                    </div>
                                    <!-- 修改 -->
                                    <div class="mb-2" v-for="(item,index) in row.edit_list" :key="index">
                                        <div v-if="Array.isArray(item.newValue) && item.field != 'universal_category_id'">{{ `“${item.name}”上传图片发生变化 ` }}</div>
                                        <div v-else-if="item.field == 'universal_category_id'">{{ `业务类型发生变化 ` }}</div>
                                        <div v-else>{{ `“${item.name}”由 ${item.oldValue} 修改为 ${item.newValue} ` }}</div>
                                    </div>
                                    <!-- 删除 -->
                                    <div class="mb-2" v-for="(item,index) in row.delete_list" :key="index">
                                        <div>{{ `“${item.name}”删除了 ` }}</div>
                                    </div>
                                    <div v-if="row.add_list.length == 0 && row.edit_list.length == 0 && row.delete_list.length == 0">-</div>
                                </div>
                                 <!-- 1.审核中 2.审核通过 3.审核驳回 -->
                                <div v-if="row.action_type == 3">
                                    <div v-show="row.content.newcontent.check_status == 1">审核中</div>
                                    <div v-if="row.content.newcontent.check_status == 2">
                                        <div>审核通过</div>
                                        <div>审核意见：{{ row.content.newcontent.reason }}</div>
                                        <div>需求可见范围：<span v-for="(item,index) in formData.cates" :key="index">{{ item.name }}{{ index<2?'、':'' }}</span></div>
                                         <!-- 新增 -->
                                        <div class="mb-2" v-for="(item,index) in row.add_list" :key="index">
                                            <div v-if="item.newValue == item.oldValue"></div>
                                            <div v-else-if="!Array.isArray(item.newValue)" class="flex align-center">{{ `“${item.name}”由 ${item.oldValue} 修改为 ${item.newValue} ` }}</div>
                                        </div>
                                        <!-- 修改 -->
                                        <div class="mb-2" v-for="(item,index) in row.edit_list" :key="index">
                                            <div v-if="Array.isArray(item.newValue) && item.field != 'universal_category_id'">{{ `“${item.name}”上传图片发生变化 ` }}</div>
                                            <div v-else-if="item.field == 'universal_category_id'">{{ `业务类型发生变化 ` }}</div>
                                            <div v-else>{{ `“${item.name}”由 ${item.oldValue} 修改为 ${item.newValue} ` }}</div>
                                        </div>
                                    </div>
                                    <div v-if="row.content.newcontent.check_status == 3">
                                        <div>审核驳回</div>
                                        <div>审核意见：{{ row.content.newcontent.reason }}</div>
                                    </div>
                                </div>
                                <div v-if="row.action_type == 4">关闭需求</div>
                                <div v-if="row.action_type == 5">{{ userInfo.real_name }} 与 {{ row.channel_extra.real_name }} 确认达成合作</div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="create_time" label="操作时间" min-width="180" />
                        <el-table-column prop="person.real_name" label="操作人" min-width="180" />
                    </el-table>
                </el-card>
            </el-tab-pane>
        </el-tabs>

    <!-- 查看记录弹窗 -->
    <el-dialog v-model="recordVisible" title="查看记录" width="500">
        <div class="flex">

            <div class="mask-content">
                <div class="mask-item hide-before hide-bottom">
                    <div class="mask-time">{{ recordTime }}</div>
                    <div class="mask-txt">查看详情</div>
                </div>
            </div>

        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="recordVisible = false">关闭</el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 对接记录弹窗 -->
    <el-dialog v-model="dockVisible" title="对接记录" width="500">
        <div class="flex">

            <div class="mask-content">
                <div class="mask-item" v-if="dockInfo.done_type">
                    <div class="mask-time">{{ dockInfo.done_time }}</div>
                    <div class="mask-txt">
                        <span class="mask-span">{{ dockInfo.user.nickname }} 与 {{ dockInfo.channelExtra.real_name }}</span>
                        确认达成合作
                    </div>
                </div>
                <div class="mask-item" v-if="dockInfo.cancel_type">
                    <div class="mask-time">{{ dockInfo.cancel_time }}</div>
                    <div class="mask-txt">
                        <span class="mask-span" v-if="dockInfo.cancel_type == 1">{{ dockInfo.user.nickname }}</span>
                        <span class="mask-span" v-if="dockInfo.cancel_type == 3">{{ dockInfo.channelExtra.real_name }}</span>
                        取消对接
                    </div>
                </div>
                <div class="mask-item hide-before">
                    <div class="mask-time">{{ dockInfo.abutment_time }}</div>
                    <div class="mask-txt">
                        <span class="mask-span">{{ dockInfo.channelExtra.real_name }}</span>
                        对单
                    </div>
                </div>
            </div>

        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="dockVisible = false">关闭</el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 合作记录弹窗 -->
    <el-dialog v-model="cooperateVisible" title="合作记录" width="500">
        <div class="flex">

            <div class="mask-content">
                <div class="mask-item" :class="{'hide-before': index == (cooperateInfo.length - 1)}" v-for="(item,index) in cooperateInfo" :key="index">
                    <div class="mask-time">{{ item.action_way_time }}</div>
                    <div class="mask-txt">
                        <span class="mask-span">{{ item.person.real_name }}</span>
                        <span v-if="item.action_way == 1"> 发起达成合作：
                            <span v-if="item.mode == 1">普通模式</span>
                            <span v-if="item.mode == 2">固定介绍费</span>
                            <span v-if="item.mode == 3">双方分成</span>
                        </span>
                        <span v-if="item.action_way == 2">已确认达成合作</span>
                        <span v-if="item.action_way == 3">已取消达成合作</span>
                        <div>合作编号：
                            <router-link v-perms="['cooperation.cooperation/detail']" :to="{ path: getRoutePath('cooperation.cooperation/detail'), query: { id: item.cooperation_id } }">
                                <el-button type="primary" link >{{ item.sn }}</el-button>
                            </router-link>
                        </div>
                    </div>
                </div>
            </div>

        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="cooperateVisible = false">关闭</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 审核通过和驳回弹窗 -->
    <check_demand v-if="isShow" v-model:show="checkState.show" :value="checkState.value" :area_id="formData.area_id" :area_name="formData.area_name" :age="formData.age" :quota="Number(formData.quota)" :credit_status="Number(formData.credit_status)"  @confirm="handleConfirmCheck"></check_demand>
    </div>
</template>
<script lang="ts" setup name="demanedNewEdit">
// import {useDictOptions} from "@/hooks/useDictOptions";
// import { productCate} from '@/api/product/product'
import { usePaging } from '@/hooks/usePaging';
import { demandDetail, demandCheck, editDemand, abutmentRecordLists } from '@/api/demand/lists';
import check_demand from './check_demand.vue'
import router, { getRoutePath } from '@/router';
import type { FormInstance } from 'element-plus'
const formRef = shallowRef<FormInstance>()
import useAppStore from '@/stores/modules/app'
const useApp = useAppStore()
const optionCity:any = useApp.optionCity;

const typeTxt = (num:any) => {
    return computed(():string=>{
        let txt = '';
        switch(num) {
        case 1: txt = `审核中`; break;
        case 2: txt = `发布中`; break;
        case 3: txt = `审核驳回`; break;
        case 4: txt = `对接中`; break;
        case 5: txt = `对接中`; break;
        case 6: txt = `已关闭`; break;
    }
        return txt;
    })
}

const creditTxt = (num:any) => {
    return computed(():string=>{
        let txt = '';
        switch(num) {
            case 0: txt = `-`; break;
            case 1: txt = `良好`; break;
            case 2: txt = `一般`; break;
            case 3: txt = `差`; break;
        }
        return txt;
    })
}
const catesTxt = (arr: any) => {
    let txt:any = []
    arr.forEach((item:any)=>{
        txt.push(item.name)
    })
    return txt.join(',')
} 
const refresh = (res:any) => {
    console.log(res)
    let arr = res.data.name.split('.');
    let arr_name = arr[arr.length - 1];
    let obj = {
        size: res.data.size,
        url: res.data.uri,
        new_size: (res.data.size / 1024 /1024).toFixed(2),
        type_link: getImgType(arr_name),
        name: res.data.name
    }
    formData.attachments.push(obj)
}

const onSee = (url:string) => {
    window.open(url)
}
const onDel = (index:number) => {
    if (isDisabled.value) {
        return false;
    }
    formData.attachments.splice(index,1);
}

// 音频文件
interface AudioItem {
  name: string;
  src: string;
  duration: number;
  new_size: number
}
 
const audioList = ref<AudioItem[]>([
//   { name: '语音 1', src: "https://files.onestep6.com/uploads/video/20250528/2025052814014426ed66784.aac", duration: 0 },
//   { name: '语音 2', src: "https://files.onestep6.com/uploads/video/20250528/2025052814014428cc57592.aac", duration: 0 },
]);
 
const isPlaying = ref<boolean[]>(audioList.value.map(() => false));
const progress = ref<number[]>(audioList.value.map(() => 0));
const audioElements = ref<HTMLAudioElement[]>([]);
 
const formatTime = (seconds: number): string => {
  const minutes = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${minutes}:${secs < 10 ? '0' : ''}${secs}`;
};
 
const togglePlay = (index: number) => {
  const audio = audioElements.value[index];
  if (isPlaying.value[index]) {
    audio.pause();
  } else {
    audio.play().catch(e => {
      console.error('播放失败:', e);
    });
  }
  isPlaying.value = isPlaying.value.map((val, i) => i === index ? !val : val);
};
 
const stopAudio = (index: number) => {
  const audio = audioElements.value[index];
  audio.pause();
  audio.currentTime = 0;
  isPlaying.value[index] = false;
  progress.value[index] = 0;
};
 
const seekAudio = (index: number, time: any) => {
  audioElements.value[index].currentTime = time;
};
 
onMounted(() => {
  
});

const startAudio = () => {
    // console.log('startAudio')
    // console.log(audioList.value)
    audioList.value.forEach((audio, index) => {
        const audioElement = new Audio(audio.src);
        audioElements.value.push(audioElement);
        // console.log(audioElement.currentTime)
        // console.log(audioElement.duration)
        audioElement.addEventListener('timeupdate', () => {
            progress.value[index] = audioElement.currentTime;
        });
    
        audioElement.addEventListener('loadedmetadata', () => {
            audio.duration = audioElement.duration;
        });
    
        audioElement.addEventListener('ended', () => {
            isPlaying.value[index] = false;
        });
    });
}
 
onUnmounted(() => {
  audioElements.value.forEach(audio => {
    audio.pause();
    audio.removeEventListener('timeupdate', () => {});
    audio.removeEventListener('loadedmetadata', () => {});
    audio.removeEventListener('ended', () => {});
  });
});

const route = useRoute()
const file_list:any = ref([])
const file_img:any = ref([])
const activeName = ref('file')
// 需求信息---------------
const formData:any = reactive({
    id: '',
    status: '',
    age: '', // 年龄
    area_id: '',
    area_name: '',
    quota: '', // 额度
    universal_category_id: [], // 业务类型 格式 [1,2,3] 1.抵押 2.信贷 3.企业贷
    work_month: '', // 现单位工作时长 单位：月份
    salary: '', // 工资
    social_security_images: [], //社保附件格式 ["a.jpg","b.jpg"]
    common_fund_images: [], // 公积金附件格式 ["a.jpg","b.jpg"]
    work_remark: '', // 工作其他情况备注
    house_address: '', // 房屋地址
    house_area: '', // 房屋面积 单位：平方米
    house_certificate_images: [], // 房产附件格式 ["a.jpg","b.jpg"]
    house_remark: '', // 房产其他情况备注
    business_license_images: [], // 营业执照附件 ["a.jpg","b.jpg"]
    business_income_tax_images: [], // 企业所得税附件 ["a.jpg","b.jpg"]
    business_public_flow_images: [], // 企业对公流水附件 ["a.jpg","b.jpg"]
    business_credit_images: [], // 企业征信附件["a.jpg","b.jpg"]
    business_remark: '', // 营业其他情况备注
    person_credit_images: [], // 个人征信附件 ["a.jpg","b.jpg"]
    other_desc: '', // 个人其他情况备注

    operation_records: [], // 操作记录
    cates: [], //业务类型
    files: [],
    universal_categories: [],
    attachments: [],
    credit_status: '',
    description: '',
    create_time: '',
    user: {
        account: '',
        real_name: ''
    },
    audio_files: []
})

const rules = reactive({
    area_id: [{required: true, message: '请选择城市', trigger: 'blur'}],
    age: [{required: true, message: '请填写年龄', trigger: 'blur'}],
    quota: [{required: true, message: '请填写所需额度', trigger: 'blur'}],
    universal_category_id: [{required: true, message: '请选择业务类型', trigger: 'blur'}],
    work_month: [{required: false, message: '请填写现单位工作时长', trigger: 'blur'}],
    salary: [{required: false, message: '请填写打卡工资（月）', trigger: 'blur'}],
    social_security_images: [{required: false, message: '请上传社保证明', trigger: 'blur'}],
    common_fund_images: [{required: false, message: '请上传公积金证明', trigger: 'blur'}],
    
    house_address: [{required: false, message: '请填写', trigger: 'blur'}],
    house_area: [{required: false, message: '请上传公积金证明', trigger: 'blur'}],
    house_certificate_images: [{required: false, message: '请上传房产证', trigger: 'blur'}],

    business_license_images: [{required: false, message: '请上传营业执照', trigger: 'blur'}],
    business_income_tax_images: [{required: false, message: '请上传企业所得税', trigger: 'blur'}],
    business_public_flow_images: [{required: false, message: '请上传企业对公流水', trigger: 'blur'}],
    business_credit_images: [{required: false, message: '请上传企业征信', trigger: 'blur'}],

    person_credit_images: [{required: false, message: '请上传个人征信', trigger: 'blur'}],
    description: [{required: true, message: '请填写需求描述', trigger: 'blur'}],
})

const defaultTab  = ref('demand_info')

const isDock = ref(true)

const cateList = [
    { id: 1, name: '抵押'},
    { id: 2, name: '信贷'},
    { id: 3, name: '企业贷'},
]

// const {optionsData} = useDictOptions<{
//   product_cate_list: any[],
// }>({
//   product_cate_list: {
//     api: productCate
//   }
// })

// 主营业务选中数据发生变化
const changeProductCate = (val: any[]) => {
  console.log(val)
  // 信贷的校验必填
  if (val.includes('2')) {
    rules.work_month[0].required = true;
    rules.salary[0].required = true;
    rules.social_security_images[0].required = true;
    rules.common_fund_images[0].required = true;
    rules.person_credit_images[0].required = true;
  } else {
    rules.work_month[0].required = false;
    rules.salary[0].required = false;
    rules.social_security_images[0].required = false;
    rules.common_fund_images[0].required = false;
    rules.person_credit_images[0].required = false;
  }
  // 房抵的校验
  if (val.includes('1')) {
    rules.house_address[0].required = true;
    rules.house_area[0].required = true;
    rules.house_certificate_images[0].required = true;
  } else {
    rules.house_address[0].required = false;
    rules.house_area[0].required = false;
    rules.house_certificate_images[0].required = false;
  }
  // 企业税贷的校验
  if (val.includes('3')) {
    rules.business_license_images[0].required = true;
    rules.business_income_tax_images[0].required = true;
    rules.business_public_flow_images[0].required = true;
    rules.business_credit_images[0].required = true;
  } else {
    rules.business_license_images[0].required = false;
    rules.business_income_tax_images[0].required = false;
    rules.business_public_flow_images[0].required = false;
    rules.business_credit_images[0].required = false;
  }
}
// 需求信息---------------

//对接信息---------------
// 查看渠道
const onChannel = (row:any) => {
    console.log(row)
    router.push({
        path: getRoutePath('channel.channel/lists'), query: { name: row.channelExtra.real_name }
    })
}
// 查看
const recordVisible = ref(false);
const recordTime = ref('')
const recordShow = (row:any) => {
    recordTime.value = row.read_time;
    recordVisible.value = true;
} 
// 对接
const dockVisible = ref(false);
const dockInfo:any = ref({})
const dockShow = (row:any) => {
    dockInfo.value = row
    dockVisible.value = true;
} 
// 合作
const cooperateVisible = ref(false);
const cooperateInfo:any = ref([{person:{real_name:''}}])
const cooperateShow = (row:any) => {
    console.log(row)
    cooperateInfo.value = row.cooperation_operation_records;
    cooperateVisible.value = true;
}
const queryParams = reactive({
    id: route.query.id,
    area_id: route.query.area_id,
    is_read: '',
    abutment_status: '',
    cooperation_status: '',
    
});
const { pager, getLists, resetPage, resetParams } = usePaging({
    fetchFun: abutmentRecordLists,
    params: queryParams
})
route.query.id && getLists()
const indexAdd = (index: number) => {
    const page = pager.page // 当前页码
    const pagesize = pager.size // 每页条数
    return index + 1 + (page - 1) * pagesize
}

//对接信息---------------

// 操作记录

// 操作记录---------------

// 只读状态
const isDisabled = ref(true)
const fieldNames:{ [key: string]: string; }  = {
    age: '年龄', // 
    quota: '所需额度', // 
    // credit_status: '征信状况',
    credit_status_desc: '征信状况',
    universal_category_id: '业务类型', // 业务类型 格式 [1,2,3] 1.抵押 2.信贷 3.企业贷
    work_month: '现单位工作时间', //  单位：月份
    salary: '打卡工资（月）', // 工资
    social_security_images: '社保', //社保附件格式 ["a.jpg","b.jpg"]
    common_fund_images: '公积金', // 公积金附件格式 ["a.jpg","b.jpg"]
    work_remark: '工作备注', // 工作其他情况备注
    house_address: '房屋地址', // 房屋地址
    house_area: '房屋面积', // 房屋面积 单位：平方米
    house_certificate_images: '房产证', // 房产附件格式 ["a.jpg","b.jpg"]
    house_remark: '房产信息备注', // 房产其他情况备注
    business_license_images: '营业执照', // 营业执照附件 ["a.jpg","b.jpg"]
    business_income_tax_images: '企业所得税', // 企业所得税附件 ["a.jpg","b.jpg"]
    business_public_flow_images: '企业对公流水', // 企业对公流水附件 ["a.jpg","b.jpg"]
    business_credit_images: '企业征信', // 企业征信附件["a.jpg","b.jpg"]
    business_remark: '经营信息备注', // 营业其他情况备注
    person_credit_images: '个人征信', // 个人征信附件 ["a.jpg","b.jpg"]
    other_desc: '个人征信备注', // 个人其他情况备注
    description: '所需描述',
    // area_id: '城市',
    area_name: '城市',
    attachments: '附件',
   
};

const userInfo = ref({
    real_name: ''
})
const getImgType = (name:any) => {
    let url = ''
    switch(name) {
        case 'docx': url = 'https://files.onestep6.com/2024/wxicon/img/file-doc.png'; break;
        case 'xlsx': url = 'https://files.onestep6.com/2024/wxicon/img/file-xls.png'; break;
        case 'pptx': url = 'https://files.onestep6.com/2024/wxicon/img/file-ppt.png'; break;
        case 'pdf': url = 'https://files.onestep6.com/2024/wxicon/img/file-pdf.png'; break;
        case 'png': url = '1'; break;
        case 'jpg': url = '1'; break;
        case 'jpeg': url = '1'; break;
        default : url = 'https://files.onestep6.com/2024/wxicon/img/file-unknow.png'; break;
    }
    return url
}
const isShow = ref(false)
// 详情
const getDetails = async () => {
    isShow.value = false;
    const data = await demandDetail({
        id: route.query.id,
        area_id: route.query.area_id
    })
    userInfo.value = data.user;
    console.log(data.user)
    console.log(userInfo.value)
    data.quota = (data.quota / 10000).toFixed(2)
    data.audio_files.map((item:any)=>{
        item.duration = 0;
        item.src = item.url;
        item.new_size = (item.size / 1024 /1024).toFixed(2)
    })
    audioList.value = data.audio_files;
    isPlaying.value = audioList.value.map(() => false)
    progress.value = audioList.value.map(() => 0)
    startAudio()
    // 处理文件字节显示为兆
    console.log(data.attachments)
    if (data.attachments.length != 0) {
        data.attachments.map((item:any)=>{
            item.new_size = (item.size / 1024 / 1024).toFixed(2);
            let arr = item.name.split('.');
			item.type_name = arr[arr.length - 1];
            item.type_link = getImgType(item.type_name)
        })
    }
    
    // 类型定义
    type ChangeRecord = {
        field: string;
        name: string;
        oldValue: any;
        newValue: any;
    };
    // 空值判断函数
    const isEmpty = (value: any): boolean => {
        if (value === null || value === undefined) return true;
        if (typeof value === 'string' && value.trim() === '') return true;
        if (typeof value === 'number' && value === 0) return true;
        if (Array.isArray(value) && value.length === 0) return true;
        return false;
    };
    // 值比较函数
    const isEqual = (a: any, b: any): boolean => {
        // 处理数组比较
        if (Array.isArray(a) && Array.isArray(b)) {
            return a.length === b.length && a.every((item, i) => isEqual(item, b[i]));
        }
        
        // 处理数字和字符串的隐式转换
        if (typeof a !== typeof b) {
            const numA = Number(a);
            const numB = Number(b);
            if (!isNaN(numA) && !isNaN(numB)) {
                return numA === numB;
            }
            return false;
        }
        
        // 处理对象比较
        if (typeof a === 'object' && a !== null && b !== null) {
            const keysA = Object.keys(a);
            const keysB = Object.keys(b);
            
            if (keysA.length !== keysB.length) return false;
            
            return keysA.every(key => 
                isEqual(a[key], b[key])
            );
        }
        
        // 处理基本类型
        return a === b;
    }
        // 主比较函数
    const compareObjects = (original: any, current: any) => {
        const added = ref<ChangeRecord[]>([]);
        const edited = ref<ChangeRecord[]>([]);
        const deleted = ref<ChangeRecord[]>([]);

        Object.keys(fieldNames).forEach((key) => {
            const oldVal = original[key];
            const newVal = current[key];
            const fieldName = fieldNames[key];

            // 新增判断
            if (isEmpty(oldVal) && !isEmpty(newVal)) {
            added.value.push({
                field: key,
                name: fieldName,
                oldValue: oldVal,
                newValue: newVal
            });
            }
            // 删除判断
            else if (!isEmpty(oldVal) && isEmpty(newVal)) {
            deleted.value.push({
                field: key,
                name: fieldName,
                oldValue: oldVal,
                newValue: newVal
            });
            }
            // 修改判断
            else if (!isEqual(oldVal, newVal)) {
            edited.value.push({
                field: key,
                name: fieldName,
                oldValue: oldVal,
                newValue: newVal
            });
            }
        });

        return { added, edited, deleted };
    };
    // 封装对比函数
    data.operation_records.map((item: any) => {
        if (item.action_type == 2 || item.action_type == 3) {
            const { added, edited, deleted } = compareObjects(item.content.oldcontent, item.content.newcontent);
            console.log(added)
            console.log(edited)
            item.add_list = added
            item.edit_list = edited
            item.delete_list = deleted
        }
    })
    

    Object.keys(formData).forEach((key) => {
        //@ts-ignore
        formData[key] = data[key]
        // if( key=='image_urls' ){
        // 	console.log(data[key],123456);
        // 	formData[key] = data[key][0]
        // }
    })
    changeProductCate(data.universal_category_id)
    isShow.value = true;
}

route.query.id && getDetails()

// 审核通过和驳回
const checkState = reactive({
    show: false,
    value: ''
})
const handleEdit = () =>{
    console.log(file_img)
    console.log(file_list)
    isDisabled.value = false; 
}
// 编辑取消
const handleCancel = () => {
    formRef.value?.clearValidate()
    isDisabled.value = true; 
    getDetails()
}
// 编辑保存
const handleSave = async () => {
    await formRef.value?.validate()
    formData.quota = Number(formData.quota) * 10000
    await editDemand(formData)
    getDetails()
    isDisabled.value = true; 
}
const handleCheck = (value : any) => {
    console.log(value)
    checkState.show = true
    checkState.value = value
}
const handleConfirmCheck = async (value : any) => {
    console.log(value);
    value.quota *= 10000;
    await demandCheck({ id: Number(route.query.id), ...value, area_id: route.query.area_id })
    checkState.show = false
    getDetails()
}

</script>
<style lang="scss" scoped>
.txt-content{
    width: 15%;
    height: 50px;
    background-color: var(--el-color-primary-light-9);
    line-height: 50px;
    text-align: center;
    border-radius: 5px;
    white-space: nowrap;
}
.arrow-left{
    width: 30px;
    height: 10px;
    background: var(--el-color-primary);
}
.arrow-container {
    position: relative;
    width: 50px; /* 容器的宽度，可以根据需要调整 */
    height: 50px; /* 容器的高度，可以根据需要调整 */
}

.arrow-container::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    width: 0;
    height: 0;
    border-top: 15px solid transparent; /* 顶部边框透明 */
    border-bottom: 15px solid transparent; /* 底部边框透明 */
    border-left: 15px solid var(--el-color-primary); /* 左边边框设置颜色 */
    transform: translateY(-50%); /* 垂直居中 */
}

.mask-content{
    padding-left: 150px;
    .mask-item{
        position: relative;
        padding-bottom: 30px;
    }
    .mask-item::before{
        content: '';
        position: absolute;
        left: -11px;
        top: 8px;
        width: 2px;
        height: 100%;
        border-radius: 50%;
        background: var(--el-color-primary);
    }
    .hide-before::before {
        content: "";
        display: none; /* 或者使用 visibility: hidden; 根据需求 */
    }
    .mask-time{
        position: relative;
    }
    .mask-time::before{
        content: '';
        position: absolute;
        left: -14px;
        top: 6px;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: var(--el-color-primary);
    }
    .mask-span{
        color: var(--el-color-primary);
        margin-right: 10px;
    }
    .hide-bottom{
        padding-bottom: 0;
    }
}
.btnR{
    position: absolute;
    right: 50px;
    top: 30px;
    z-index: 999;
}
.content{
    display: flex;
    flex-wrap: wrap;
    .content-item{
        position: relative;
        margin-right: 10px;
        margin-bottom: 10px;
        cursor: pointer;
        .item-del{
            position: absolute;
            right: -12px;
            top: -12px;
            width: 25px;
            height: 25px;
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 10;
            .del-img{
                display: block;
                width: 14px;
                height: 14px;
            }
        }
        .item-content{
            display: flex;
            align-items: center;
            padding:4px 8px;
            border: 1px solid #CCCCCC;
            border-radius: 10px;
        }
        .item-type{
            flex-shrink: 0;
            display: block;
            width: 28px;
            height: 36px;
            margin-right: 8px;
        }
        .item-img{
            display: block;
            width: 80px;
            height: 80px;
        }
    }
}
.audio-card {
    width: 30%;
    margin-bottom: 20px;
    margin-right: 20px;
}
 
.audio-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
 
.audio-controls {
  display: flex;
  gap: 0.5rem;
}
 
.progress-slider {
  width: 100%;
  margin-bottom: px;
}
 
.time-display {
  font-size: 16px;
  color: #666;
  display: block;
  text-align: right;
}
.content-yw{
    width: 360px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
}
</style>